import decimal
import random
import time

import requests

from orderSharing.retailOrderSharing import RetailOrderSharing


class ActivityOrderSharing:

    def __init__(self):
        self.retailOrderSharing = RetailOrderSharing()

    # 万人团退款、分润核对
    def participate_in_activities(self):
        self.retailOrderSharing.session.commit()
        userList = self.retailOrderSharing.session.execute("select ru.user_id, u.mobile, ua.id, ru.bind_retail_store_id, ru.current_retail_store_id\
                                    from retail_users ru\
                                    inner join user_addresses ua on ru.user_id = ua.user_id\
                                    inner join users u on u.id = ru.user_id\
                                    where ru.is_real_name = 1 and ua.is_default = 1").fetchall()
        userTotal = random.randint(5, 15)

        activityList = requests.request("GET",
                                        url="https://test.api.vodeshop.com/api/retail/activity/group/goods/activity-list/1?limit=15&page=1",
                                        headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                 "authorization":"Bearer "}).json()["data"]["data"]
        activityIndex = random.randint(0, len(activityList) - 1)
        activity = activityList[activityIndex]
        print("activity：", activity)

        activityDetail = requests.request("GET",
                                        url="https://test.api.vodeshop.com/api/retail/activity/show/"+str(activity["id"]),
                                        headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                 "authorization": "Bearer "}).json()["data"]
        activitySku = activityDetail["activity_goods"]["retail_activity_goods_sku"][0]
        print("activitySku：", activitySku)

        self.retailOrderSharing.session.commit()
        retail_activity_goods_skus = self.retailOrderSharing.session.execute(
            "select rag.join_num, rags.cost_price, rags.price, rags.platform_profit_price\
                        from retail_activity_groups rag\
                        inner join retail_activity_goods_skus rags on rag.retail_activity_goods_id = rags.retail_activity_goods_id\
                        where rag.retail_activity_goods_id = :activityId",
            params={"activityId": activity["id"]}).first()

        self.retailOrderSharing.session.commit()
        retail_sets = self.retailOrderSharing.session.execute(
            "select credit_ratio, bind_store_ratio, current_store_ratio, agent_ratio from retail_sets limit 1").first()

        subRatioList = []
        for num in range(1, 3):
            self.retailOrderSharing.session.commit()
            sub_ratio = self.retailOrderSharing.session.execute(
                "select sub_ratio from retail_vip_levels where vip_level = :vipLevel limit 1",
                params={"vipLevel": num}).first()
            subRatioList.append(sub_ratio[0])

        placeUserList = []
        for user in userList[:userTotal]:

            self.retailOrderSharing.session.commit()
            retail_group_stage_id = self.retailOrderSharing.session.execute(
                "select rag.retail_group_stage_id, rags.cost_price, rags.price, rags.platform_profit_price\
                        from retail_activity_groups rag\
                        inner join retail_group_activity_stages rgas on rag.retail_group_stage_id = rgas.id\
                        where rag.retail_activity_goods_id = :activityId",
                params={"activityId": activity["id"]}).first()

            if retail_group_stage_id == None:
                retail_group_stage_id = (
                0, retail_activity_goods_skus[1], retail_activity_goods_skus[2], retail_activity_goods_skus[3])

            requests.request("POST", url="https://test.api.vodeshop.com/api/sms/user-login", json={"mobile": user[1]})
            time.sleep(5)

            print("user：", user)
            userToken = requests.request("POST", url="https://test.api.vodeshop.com/api/auth/login/mobile",
                                         json={"mobile": user[1], "password": "", "code": "111111"}).json()
            print("userToken：", userToken)
            token = userToken["data"]["token_type"] + " " + userToken["data"]["access_token"]

            # 核对会员立减需要
            againActivityList = requests.request("GET",
                                            url="https://test.api.vodeshop.com/api/retail/activity/group/goods/activity-list/1?limit=15&page=1",
                                            headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                     "authorization": token}).json()["data"]["data"]
            againActivity = againActivityList[activityIndex]

            goodTotal = random.randint(2, 3)

            orderCheck = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/check-order",
                                          headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                   "authorization": token},
                                          json={"retail_goods_id": [activityDetail["id"]], "address_id": user[2]}).json()
            confirm = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/activity/order/confirm",
                                       headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                                "authorization": token},
                                       json={"activity_goods_id":activity["id"],"activity_goods_sku_id":activitySku["id"],"quantity":goodTotal,"address_id":user[2]}).json()
            activity_goods_sku = confirm["data"]["goods"][0]["items"][0]["goods_sku"]
            original_amount = (decimal.Decimal(activity_goods_sku["price"]) + decimal.Decimal(
                orderCheck["data"][0]["addr_carriage"]) - decimal.Decimal(str(activity_goods_sku["sub_price"]))) * goodTotal
            print("original_amount：", original_amount)

            self.retailOrderSharing.session.commit()
            vip_level = self.retailOrderSharing.session.execute(
                "select vip_level from retail_vips where user_id = :userId limit 1",
                params={"userId": user[0]}).first()
            print("vip_level：", vip_level)

            if vip_level != None:
                proportion = 0

                if vip_level[0] == 1:
                    proportion = subRatioList[0]

                elif vip_level[0] == 2:
                    proportion = subRatioList[1]

                elif vip_level[0] == 3:
                    proportion = 100 - retail_sets[3]

                if decimal.Decimal(againActivity["sub_price"]) != (
                        retail_group_stage_id[2] - retail_group_stage_id[1] - retail_group_stage_id[3]) * \
                        proportion / 100:
                    print("{}万人团活动列表会员立减错误，预期{}，实际{}".format(activity["id"],
                                                          (retail_group_stage_id[2] - retail_group_stage_id[1] - retail_group_stage_id[3]) *
                                                          proportion / 100, decimal.Decimal(againActivity["sub_price"])))

                if decimal.Decimal(confirm["data"]["sub_price"]) != (
                        retail_group_stage_id[2] - retail_group_stage_id[1] - retail_group_stage_id[3]) * proportion / 100 * goodTotal:
                    print("{}结算页面会员立减错误，预期{}，实际{}".format(activity["id"], (
                            retail_group_stage_id[2] - retail_group_stage_id[1] - retail_group_stage_id[3]) * proportion / 100 * goodTotal,
                                                          decimal.Decimal(confirm["data"]["sub_price"])))

            activityOrder = requests.request("POST", url="https://test.api.vodeshop.com/api/retail/activity/group/join",
                                     headers={"x-request-from": "web", "x-requested-with": "XMLHttpRequest",
                                              "authorization": token},
                                     json={"activity_goods_id":activity["id"],"activity_goods_sku_id":activitySku["id"],"quantity":goodTotal,"address_id":user[2],"group_id":None,"pay_type":1}).json()

            time.sleep(2)
            self.retailOrderSharing.session.commit()
            order_sn = self.retailOrderSharing.session.execute(
                "select order_sn from payments where user_id = :userId and targetable_id =:targetableId order by created_at desc limit 1",
                params={"userId": user[0], "targetableId": activityOrder["data"]["order_id"]}).first()
            print("order_sn：", order_sn)

            payment = requests.request("POST", url="https://test.api.vodeshop.com/api/v2/test/notifyyyy",
                                   data={"out_trade_no": order_sn[0], "trade_no": order_sn[0],
                                         "total_amount": "1"}).json()
            print("payment：", payment)

            if activityOrder["code"] == 0 and payment["code"] == 0:
                user[5] = activityOrder["data"]["order_id"]
                user[6] = decimal.Decimal(orderCheck["data"][0]["addr_carriage"])
                user[7] = original_amount
                user[8] = retail_group_stage_id[0]
                user[9] = goodTotal
                user[10] = vip_level
                placeUserList.append(user)

        self.retailOrderSharing.session.commit()
        retail_group_activity_stages = self.retailOrderSharing.session.execute(
            "select id, order_quantity, cost_price, price, platform_profit_price from retail_group_activity_stages where retail_activity_goods_id = :activityId order by `level` asc",
            params={"activityId": activity["id"]}).fetchall()

        currentStageId = 0
        for i in range(0, len(retail_group_activity_stages)-2):
            if retail_activity_goods_skus[0] + len(placeUserList) < retail_group_activity_stages[0][1]:
                currentStageId = 0
            elif retail_activity_goods_skus[0] + len(placeUserList) >= retail_group_activity_stages[i][1] and retail_activity_goods_skus[0] + len(placeUserList) < retail_group_activity_stages[i+1][1]:
                currentStageId = retail_group_activity_stages[i][0]
            elif retail_activity_goods_skus[0] + len(placeUserList) >= retail_group_activity_stages[len(retail_group_activity_stages)-1][1]:
                currentStageId = retail_group_activity_stages[len(retail_group_activity_stages)-1][0]

        self.retailOrderSharing.session.commit()
        activity_stage = self.retailOrderSharing.session.execute(
            "select rgas.id, rgas.cost_price, rgas.price, rgas.platform_profit_price\
                     from retail_group_activity_stages rgas\
                     inner join retail_activity_groups rag on rgas.id = rag.retail_group_stage_id\
                     where rag .retail_activity_goods_id = :activityId",
            params={"activityId": activity["id"]}).first()
        if activity_stage == None:
            activity_stage = (0, retail_activity_goods_skus[1], retail_activity_goods_skus[2], retail_activity_goods_skus[3])

        if activity_stage[0] != currentStageId:
            print("{}当前阶段错误，预期{}，实际{}".format(activity["id"], currentStageId, activity_stage[0]))
            raise

        time.sleep(10)
        self.retailOrderSharing.session.commit()
        self.retailOrderSharing.session.execute(
            "update retail_activity_goods rag\
                     inner join retail_activity_groups rap on rag.id = rap.retail_activity_goods_id\
                     set rag.end_at = now(), rap.expired_at = now()\
                     where rag.id = :activityId",
            params={"activityId": activity["id"]})
        self.retailOrderSharing.session.commit()

        time.sleep(300)
        for placeUser in placeUserList:

            crossStore = False
            self.retailOrderSharing.session.commit()
            retail_store_id = self.retailOrderSharing.session.execute(
                "select ro.retail_store_id, rog.id\
                        from retail_orders ro\
                        inner join retail_order_goods rog on rog.retail_order_id = ro.id\
                        where ro.id = :orderId limit 1", params={"orderId": placeUser[5]}).first()

            amount = None
            union, partner = 1, 1
            if placeUser[10] != None:
                if placeUser[10][0] == 1:
                    union += 1
                    amount = (activity_stage[2] + placeUser[6] - (
                                activity_stage[2] - activity_stage[1] -
                                activity_stage[3]) * subRatioList[0] / 100) * placeUser[9]
                elif placeUser[10][0] == 2:
                    partner += 1
                    amount = (activity_stage[2] + placeUser[6] - (
                                activity_stage[2] - activity_stage[1] -
                                activity_stage[3]) * subRatioList[1] / 100) * placeUser[9]
                elif placeUser[10][0] == 3:
                    amount = (activity_stage[2] + placeUser[6] - (activity_stage[2] - activity_stage[1] - activity_stage[3]) * (100 - retail_sets[3]) / 100) * placeUser[9]
            else:
                amount = (activity_stage[2] + placeUser[6]) * placeUser[9]

            if activity_stage[0] != placeUser[8]:

                self.retailOrderSharing.session.commit()
                refund_price = self.retailOrderSharing.session.execute(
                    "select refund_price from retail_group_joins where user_id = :userId and retail_order_id = :orderId and retail_activity_goods_id = :activityId",
                    params={"userId": placeUser[0], "orderId": placeUser[5], "activityId": activity["id"]}).first()
                if refund_price[0] != placeUser[7] - amount:
                    print("{}退款错误，预期{}，实际{}".format(placeUser[5], placeUser[7] - amount, refund_price[0]))

            self.retailOrderSharing.check_members_sharing(placeUser[0], retail_store_id[1], amount, subRatioList,
                                       (activity_stage[2] - activity_stage[1] - activity_stage[3]) * placeUser[9],
                                       retail_sets, 1, union, partner, crossStore, placeUser[3], retail_store_id[0], placeUser[10])


if __name__ == "__main__":
    ActivityOrderSharing().participate_in_activities()





